import uuid
import requests
from django.http import JsonResponse
from django.shortcuts import redirect
from django.conf import settings
from Login.models import User, ThirdPartyLogin, UserProfile
from utils.JWTTool import JwtUtils

# Gitee OAuth 配置
GITEE_CONFIG = {
    'CLIENT_ID': 'dafafe27d3939e0d146b20e6ea92aed17201dd7f6243dc00af7931b7ac3a0b9b',
    'CLIENT_SECRET': 'e36b406181789998974801299bb59e4f3331173ad944344b9d54ebfabde2147b',
    'REDIRECT_URI': 'http://localhost:8000/gitee/callback',
    'SCOPE': 'user_info'
}

class GiteeOAuth:
    """Gitee OAuth类"""
    
    @staticmethod
    def get_authorize_url(state=None):
        """生成授权URL"""
        if not state:
            state = str(uuid.uuid4())
        
        authorize_url = (
            f"https://gitee.com/oauth/authorize?"
            f"client_id={GITEE_CONFIG['CLIENT_ID']}&"
            f"redirect_uri={GITEE_CONFIG['REDIRECT_URI']}&"
            f"response_type=code&"
            f"scope={GITEE_CONFIG['SCOPE']}&"
            f"state={state}"
        )
        
        return authorize_url, state
    
    @staticmethod
    def handle_callback(request):
        """处理回调"""
        code = request.GET.get('code')
        state = request.GET.get('state')
        
        print(f"[Gitee OAuth] 回调参数: code={code}, state={state}")
        
        if not code:
            print("[Gitee OAuth] 错误: 缺少授权码")
            return JsonResponse({'error': '缺少授权码'}, status=400)
        
        try:
            # 获取access_token
            print("[Gitee OAuth] 请求access_token...")
            token_response = requests.post('https://gitee.com/oauth/token', data={
                'grant_type': 'authorization_code',
                'code': code,
                'client_id': GITEE_CONFIG['CLIENT_ID'],
                'client_secret': GITEE_CONFIG['CLIENT_SECRET'],
                'redirect_uri': GITEE_CONFIG['REDIRECT_URI']
            })
            
            print(f"[Gitee OAuth] Token响应状态: {token_response.status_code}")
            if token_response.status_code != 200:
                print(f"[Gitee OAuth] Token响应内容: {token_response.text}")
                return JsonResponse({'error': '获取访问令牌失败'}, status=400)
            
            token_data = token_response.json()
            access_token = token_data.get('access_token')
            
            if not access_token:
                return JsonResponse({'error': '访问令牌为空'}, status=400)
            
            # 获取用户信息
            user_response = requests.get(
                f'https://gitee.com/api/v5/user?access_token={access_token}'
            )
            
            if user_response.status_code != 200:
                return JsonResponse({'error': '获取用户信息失败'}, status=400)
            
            user_data = user_response.json()
            
            # 创建或获取用户
            gitee_id = str(user_data.get('id'))
            username = user_data.get('login', f'gitee_{gitee_id}')
            email = user_data.get('email', '')
            avatar = user_data.get('avatar_url', '')
            
            print(f"[Gitee OAuth] 用户数据: username={username}, email='{email}', gitee_id={gitee_id}")
            
            # 检查是否已有该Gitee用户
            try:
                third_party = ThirdPartyLogin.objects.get(
                    platform='gitee',
                    platform_user_id=gitee_id
                )
                user = third_party.user
                print(f"[Gitee OAuth] 找到现有用户: {user.username}")
            except ThirdPartyLogin.DoesNotExist:
                # 处理email问题：如果为空或已存在，生成唯一email
                if not email or email.strip() == '':
                    email = f'gitee_{gitee_id}@example.com'
                    print(f"[Gitee OAuth] email为空，生成默认email: {email}")
                else:
                    # 检查email是否已被使用
                    if User.objects.filter(email=email).exists():
                        original_email = email
                        email = f'gitee_{gitee_id}_{original_email}'
                        print(f"[Gitee OAuth] email已存在，生成新email: {email}")
                
                # 确保username唯一
                original_username = username
                counter = 1
                while User.objects.filter(username=username).exists():
                    username = f'{original_username}_{counter}'
                    counter += 1
                    
                if username != original_username:
                    print(f"[Gitee OAuth] username已存在，生成新username: {username}")
                
                print(f"[Gitee OAuth] 准备创建用户: username={username}, email={email}")
                
                # 创建新用户
                user = User.objects.create_user(
                    username=username,
                    email=email
                )
                
                # 创建用户资料
                UserProfile.objects.create(
                    user=user,
                    nickname=user_data.get('name', username),
                    avatar=avatar
                )
                
                # 创建第三方登录记录
                ThirdPartyLogin.objects.create(
                    platform='gitee',
                    platform_user_id=gitee_id,
                    user=user,
                    access_token=access_token,
                    platform_user_info=user_data
                )
            
            # 生成JWT token
            token = JwtUtils.generate_token(user.id)
            
            print(f"[Gitee OAuth] JWT token生成成功: {token[:20]}...")
            
            # 重定向到前端，携带token
            frontend_url = f"http://localhost:5173/home?token={token}"
            print(f"[Gitee OAuth] 重定向到: {frontend_url}")
            return redirect(frontend_url)
            
        except Exception as e:
            import traceback
            print(f"[Gitee OAuth] 异常: {str(e)}")
            print(f"[Gitee OAuth] 异常详情: {traceback.format_exc()}")
            
            # 根据异常类型提供更友好的错误信息
            error_msg = str(e)
            if "UNIQUE constraint failed" in error_msg:
                if "user.email" in error_msg:
                    error_msg = "邮箱地址冲突，请联系管理员"
                elif "user.username" in error_msg:
                    error_msg = "用户名冲突，请联系管理员"
                else:
                    error_msg = "用户信息冲突，请联系管理员"
            elif "获取用户信息失败" in error_msg:
                error_msg = "获取Gitee用户信息失败，请稍后重试"
            elif "获取访问令牌失败" in error_msg:
                error_msg = "Gitee授权失败，请稍后重试"
            else:
                error_msg = "登录过程中发生错误，请稍后重试"
                
            print(f"[Gitee OAuth] 重定向错误信息: {error_msg}")
            error_url = f"http://localhost:5173/?error=gitee_login_failed&msg={error_msg}"
            return redirect(error_url)
